'''
Created on 2011-1-31

@author: zarra
'''
#from utils import ExprActionManager
from model.fghisdb import fghisdb,Doctor_Advice,Drug_Info
from model.drug_post import drug,Drug_Post
from datetime import datetime
import json

class Drug_Filter(object):
    def __init__(self):
        pass
    def patient_used_drug_list(self,patient_id):
        patient_id=str(patient_id)
        s=fghisdb()
        result=s.query(Doctor_Advice.drug_id)\
        .filter(Doctor_Advice.patient_id == patient_id)\
        .filter(Doctor_Advice.type.in_(Doctor_Advice.drug_types) )\
        .all()
        
        if len(result)<1:
            {'success':False}
        ids = [id[0] for id in result]
        
        result = s.query(Drug_Info).filter(Drug_Info.id.in_(ids)).all()
        
        s.close()
        return  {'success':True,'data':result}
    def drug_report_by_id(self,report_id):
        s=drug()
        report = s.query(Drug_Post).filter(Drug_Post.id == report_id).first()
        if report != None:
            report.fields = json.loads(report.fields)
            report.drugs = json.loads(report.drugs)
        s.close()
        return {'success':report !=None,'report':report}
    def drug_report_merge(self,patient_id,drugs,fields,report_id = None):
        drugs = json.dumps(drugs)
        fields = json.dumps(fields)
        
        report = Drug_Post()
        report.id = report_id
        report.patient_id = patient_id
        report.drugs = drugs
        report.fields = fields
        #report.context = context
        report.last_modify_time = datetime.now()
        success = False
        s=drug()
        try:
            report = s.merge(report)
            success = True
        except:
            pass
        print report.id
        s.flush()
        s.commit()
        #s.close()
        print report.id
        return {'success':success}
        
        
        